#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "networkmonitor.h"
#include "basestationmodel.h"
#include "alarmmodel.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    // 创建数据模型
    NetworkMonitor monitor;
    BaseStationModel baseStationModel;
    AlarmModel alarmModel;

    // 连接基站告警信号到 AlarmModel（包含完整基站信息）
    QObject::connect(&baseStationModel, &BaseStationModel::stationAlarm,
                     [&baseStationModel, &alarmModel](const QString &stationId, const QString &message, const QString &severity) {
        // 查找基站详细信息
        for (int i = 0; i < baseStationModel.rowCount(); i++) {
            QVariantMap info = baseStationModel.getStationInfo(i);
            if (info["stationId"].toString() == stationId) {
                // 使用带详细信息的方法添加告警
                alarmModel.addAlarmWithDetails(
                    stationId,
                    message,
                    severity,
                    info["stationName"].toString(),
                    info["latitude"].toDouble(),
                    info["longitude"].toDouble(),
                    info["signalStrength"].toDouble(),
                    info["connectedUsers"].toInt(),
                    info["status"].toString()
                );
                return;
            }
        }
        // 如果没找到基站信息，使用简单方法
        alarmModel.addAlarm(stationId, message, severity);
    });
    
    // 连接基站统计信号到 NetworkMonitor
    QObject::connect(&baseStationModel, &BaseStationModel::statisticsChanged,
                     &monitor, &NetworkMonitor::setStatistics);
    
    // 设置总基站数
    monitor.setTotalStations(baseStationModel.rowCount());

    QQmlApplicationEngine engine;

    // 注册上下文属性
    engine.rootContext()->setContextProperty("networkMonitor", &monitor);
    engine.rootContext()->setContextProperty("baseStationModel", &baseStationModel);
    engine.rootContext()->setContextProperty("alarmModel", &alarmModel);

    // 使用 loadFromModule 加载主 QML
    engine.loadFromModule("MonitorApp", "Main");

    if (engine.rootObjects().isEmpty())
        return -1;

    // 启动监控
    monitor.startMonitoring();

    return app.exec();
}

